from sqlalchemy import Column, Integer, String, Text
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy import create_engine
from kindle_app import app
from sqlalchemy.ext.declarative import declarative_base
from flask_login import UserMixin
from kindle_app import login_manager


engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI'], convert_unicode=True)
db_session = scoped_session(sessionmaker(autocommit=False,
                                         autoflush=False,
                                         bind=engine))
Model = declarative_base(name='Model')
Model.query = db_session.query_property()


def init_db():
    Model.metadata.create_all(bind=engine)


class User(Model, UserMixin):
    __tablename__ = 'User'
    id = Column(Integer, primary_key=True)
    userName = Column(Integer, index=True, unique=True)
    emailAddress = Column(String(120), index=True, unique=True, default='None')
    password = Column(String(230), index=True, unique=True)

    def is_authenticated(self):
        return True

    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    def get_id(self):
        return str(self.id)


@login_manager.user_loader
def load_user(id):
    return User.query.get(int(id))


class Articles(Model):
    __tablename__ = 'Articles'
    id = Column(Integer, primary_key=True)
    author = Column(String(10))
    title = Column(String(20), index=True)
    content = Column(Text(1000))
    time = Column(String(20))


if __name__ == "__main__":
    init_db()
    pass
